package com.example.fw;

import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import com.example.fw.AdminHelper;


public class ApplicationManager {
	
	private WebDriver driver;
	public String baseUrl;
	private Properties properties;
	private HibernateHelper hibernateHelper;
	private AccountHelper accountHelper;
	private MailHelper mailHelper;
	private JamesHelper jamesHelper;
	private NavigationHelper navigationHelper;
	private UserHelper userHelper;
	private FtpHelper ftpHelper;
	private AdminHelper adminHelper;

	public ApplicationManager(Properties i_properties){
		this.properties = i_properties;
	}

	public void stop() {
		driver.quit();
		
		ftpHelper.restoreFile(properties.getProperty("ftp.configFile"+".bak")
							, properties.getProperty("ftp.configFile"));
	}
	
	
	public HibernateHelper getHibernateHelper(){
		if (hibernateHelper==null)
			hibernateHelper = new HibernateHelper(this);
		
		return hibernateHelper;
	}

	public AccountHelper getAccountHelper() {
		if (accountHelper==null)
			accountHelper = new AccountHelper(this);
		
		return accountHelper;
	}
	
	public WebDriver getWebDriver() {
		String browser = properties.getProperty("browser");

		if ( driver == null ){
			if (browser.equals("firefox")){
				driver = new FirefoxDriver();
			}
			else if (browser.equals("ie")){
				driver = new InternetExplorerDriver();
			}
			else {
				throw new Error("Unsupported browser: "+browser);
			}
		}
        baseUrl = properties.getProperty("baseURL");
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.get(baseUrl);

        return driver;
	}
	
	public String getProperty(String key){
		return properties.getProperty(key);
	}

	public MailHelper getMailHelper() {
		if (mailHelper==null)
			mailHelper = new MailHelper(this);
		
		return mailHelper;
	}

	public JamesHelper getJamesHelper() {
		if (jamesHelper==null)
			jamesHelper = new JamesHelper(this);

		return jamesHelper;
	}

	public NavigationHelper getNavigationHelper() {
		if (navigationHelper == null)
			navigationHelper = new NavigationHelper(this);
		return navigationHelper;
	}

	public UserHelper getUserHelper() {
		if (userHelper == null)
			userHelper = new UserHelper(this);
		return userHelper;
	}

	public FtpHelper getFtpHelper() {
		if (ftpHelper == null)
			ftpHelper = new FtpHelper(this);
		return ftpHelper;
	}

	public AdminHelper AdminHelper() {
		if (adminHelper == null)
			adminHelper = new AdminHelper(this);
		return adminHelper;
	}
}
